package cn.edu.zxj.ojspring.util;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description：文件读写相关的工具类
 *
 * @author: zxj
 * @date: 2024-02-20
 * @time: 13:36:45
 */
public class FileUtils {
    /**
     * @description: 从 fromFilePath 对应的文件中读取内容, 放回一个字符串
     **/
    public static String readFile(String fromFilePath) {
        try (FileReader inputStream = new FileReader(fromFilePath)) {
            StringBuilder tmp = new StringBuilder();
            while (true) {
                int ch = inputStream.read();
                if (ch == -1) {
                    break;
                }
                tmp.append((char)ch);
            }
            return tmp.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    /**
     * @description: 向 toFilePath 对应的文件中写入 content 内容
     **/
    public static void writeContentToFile(String toFilePath,String content) {
        if (content == null) {
            return;
        }
        try (FileWriter outputStream = new FileWriter(toFilePath)){
            outputStream.write(content);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
